import os
import numpy as np
import util


def to_split(file) -> list:
    lz = file.readlines()
    ret = []
    for line in lz:
        # line = re.sub(r'[^\w\s\d-]', '', line)
        word_list = line.split()
        ret.extend(word_list)
    return ret


def search_index(hit_files: dict):
    context_len = 10
    for filename in hit_files:
        path = 'file'
        f = open(path + os.sep + filename, 'r', encoding='utf8')
        file_split = to_split(f)
        calc_similarity(hit_files[filename], file_split)
        for hit_pos in hit_files[filename]:
            print(hit_files[filename])
            print(filename, end='\t')
            print('...', end='')
            start_pos = hit_pos - (context_len - 1)
            if start_pos < 0:
                start_pos = 0
            end_pos = hit_pos + context_len
            if end_pos > len(file_split) - 1:
                end_pos = len(file_split) - 1
            for i in range(start_pos, hit_pos):
                print(file_split[i], end=' ')
            print(util.OutColors.CRED + file_split[hit_pos] + util.OutColors.CEND, end=' ')
            for i in range(hit_pos + 1, end_pos):
                print(file_split[i], end=' ')
            print(file_split[end_pos] + '...')
        f.close()


#def search_inverse(keyword: str, inverse: util.InvertedIndex):
#    return inverse.search(keyword)


def calc_similarity(hit_list, file_split: list):
    vector_namespace = [0 for i in range(len(file_split))]
    for hit_pos in hit_list:
        vector_namespace[hit_pos] = 1
        print(hit_pos)
    print(vector_namespace)


def search(keyword: str, inverse: util.InvertedIndex, index: util.Index):
    # todo
    # 直接输出，并返回结果
    hit_files = inverse.search(keyword)
    search_index(hit_files)
